package Prog.Objets;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Vector;
import java.util.regex.Pattern;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.QualifiedName;
import org.eclipse.core.runtime.Status;
import org.eclipse.jface.dialogs.ErrorDialog;
import org.eclipse.jface.preference.IPreferenceStore;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.widgets.Display;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IFileEditorInput;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.console.ConsolePlugin;
import org.eclipse.ui.console.IConsole;
import org.eclipse.ui.console.IConsoleConstants;
import org.eclipse.ui.console.IConsoleManager;
import org.eclipse.ui.console.IConsoleView;
import org.eclipse.ui.console.MessageConsole;
import org.eclipse.ui.console.MessageConsoleStream;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import Plugin_Reprise.Activator;
import Plugin_Reprise.console.MessageConsoleStream2out;
import Plugin_Reprise.editors.run_editor;
import Plugin_Reprise.preferences.PreferenceConstants;
import Plugin_Reprise.properties.SamplePropertyPage;

public  class Utils {
		
	private static final String DEFAULT_CONSOLE_NAME = "Reprise UV-SE";
	private static final Color COLOR_RED;
	static {
		Display device = Display.getCurrent();
		COLOR_RED = new Color(device, 255, 0, 0);
	}
	
	public static String getDate(){
		Date maintenant = new Date(); 
		SimpleDateFormat formatDateJour = new SimpleDateFormat("dd/MM/yyyy kk:mm:ss"); 
		String dateFormatee = formatDateJour.format(maintenant); 
		return dateFormatee;
	}
	
	public static IProject getCurrentProject(){    
		IEditorPart  editorPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
			if(editorPart  != null)
			 {
			 IFileEditorInput input = (IFileEditorInput) editorPart.getEditorInput();
			 IFile file = input.getFile();
			 IProject activeProject =file.getProject();
			 return activeProject;
			 }
			return null;
   
    }
	
	public static void WriteHistorique(String ligne,String FichierName,String effaceHisto){
		try {		
			IPreferenceStore prefs = Activator.getDefault().getPreferenceStore();
			String pathlog = prefs.getString(PreferenceConstants.GENE_Constants.PATH_SUIVI_REPRISE);

			String fichierlog =pathlog + File.separator+ (FichierName) ;
			FileWriter bws = new FileWriter(fichierlog, true);
			
			bws.write(ligne+"<br/>"+System.getProperty("line.separator" ));
			bws.flush();
			bws.close();
			
			 fichierlog =pathlog + File.separator+ ("historique.php") ;
			 BufferedReader br = new BufferedReader(new FileReader(fichierlog));
			 String line="";
			 String lastLine="";
			 String effaceHisto2=effaceHisto;
			 if (effaceHisto2==null || effaceHisto2.equals("")){
				 effaceHisto2="a1z2e3r4t5y6ufsdf45487sd54sd5677u21df1g564fg56df4g234di8o9";
			 }
			 Vector<String> outhisto=new Vector<String>();
			 while ((line = br.readLine()) != null) {
			    if (!lastLine.equals(line) && (line.equals("<br/>") || !line.contains(effaceHisto2))) {
			    	outhisto.add(line);
			    	lastLine=line;
			    }
			 }
			 br.close();
			 
			 outhisto.add(ligne+"<br/>");
			 bws = new FileWriter(fichierlog, false);
			 for (String lig : outhisto) {
				bws.write(lig+System.getProperty("line.separator" ));
			 }
			 
			 bws.flush();
			 bws.close();
			
		} catch (IOException e1) {
		}		
	}
	
	public static Vector<Noeud_For_Html> recursIressourceChildHtml2(String currentnoeud,IResource res,Vector<Noeud_For_Html> vals, run_editor thi, MessageConsoleStream out,String suffixe){
		try {
			String pathcomplet=currentnoeud+File.separator+res.getName();
			
			Noeud_For_Html n= new Noeud_For_Html();
			n.MenuPath=pathcomplet;
			n.MenuLibelle=res.getName();
			
	    	if (res.getType()==IResource.PROJECT){
	    		n.TypeNoeud="Projet";
	        	IResource[] resenf;
				resenf = ((IProject) res).members();
				String suffi = res.getPersistentProperty(new QualifiedName("",SamplePropertyPage.UV_PROPERTY3));
				n.colTableSuffixeOracle=suffi;
				vals.add(n);
				for(IResource rr:resenf){
	        		recursIressourceChildHtml2(pathcomplet,rr,vals, thi, out,suffi);
	        	}
        	
	    	}
	    	if (res.getType()==IResource.FOLDER) {
	    		n.TypeNoeud="Dossier";
	    		IResource[] resenf= ((IFolder) res).members();
	    		n.colTableSuffixeOracle=suffixe;
	    		vals.add(n);
	        	for(IResource rr:resenf){
	        		recursIressourceChildHtml2(pathcomplet,rr,vals, thi, out,suffixe);
	        	}

	    	}
	    	if (res.getType()==IResource.FILE){
	    		
	    		if (pathcomplet.endsWith(".trf")) {
	    			n.TypeNoeud="Fichier_TRF";
	    			Utils ut =new Utils();
	    			
	    			IFile ff=ut.recursIressourceChildExec(pathcomplet,currentnoeud,res,new Vector<String>());
	    			Element xmlfile=bytestodocxml(ff);
					if (xmlfile!=null && xmlfile.getName().equals("TRF_PARAM")){
						 String fichieruv=(xmlfile.getAttribute("FICHIERUV").getValue());
						 n.UVTablePrincName=fichieruv;
						 n.MenuPath=pathcomplet;
						 n.MenuLibelle=res.getName();
						 ObjetUniverse objUV =new ObjetUniverse(thi,out);
						 objUV.setPathPHP(currentnoeud.replaceAll(Pattern.quote(File.separator), "_")+"_");
						 objUV.ChargementDesColonnes(xmlfile.getChild("Colonnes"), null,null);
						 objUV.DescSynchronisationUVOracle2(fichieruv,suffixe,vals,pathcomplet,res.getName());
						
					}
	    		}
	    		
	    		if (pathcomplet.endsWith(".sql")) {		
	    			Utils ut =new Utils();
	    			IFile ff=ut.recursIressourceChildExec(pathcomplet,currentnoeud,res,new Vector<String>());
	    			String textfile=bytestoTextfile(ff);
	    			n.TypeNoeud="Fichier_SQL";
	    			if (textfile.contains("POUR CONTROLE")) {
	    				n.TypeNoeud+="_POUR_CONTROLE";
	    				}
    				n.MenuLibelle=ff.getName();
    				n.MenuPath=ff.getFullPath().toString();
    				
    				IPreferenceStore prefs =Activator.getDefault().getPreferenceStore();
    				String pathpref=prefs.getString(PreferenceConstants.CSV_Constants.CSV_PATHEXPORT);
    				String pathlog = prefs.getString(PreferenceConstants.GENE_Constants.PATH_SUIVI_REPRISE);
    				n.CompteOracle=prefs.getString(PreferenceConstants.Oracle_Constants.ORA_USER);
	    			n.pathlog=pathlog;
	    			n.pathexportcsv=pathpref;
	    			vals.add(n);
	    			String[] testlines = textfile.split(System.getProperty("line.separator" ));
	    			for (String line : testlines) {
						n=new Noeud_For_Html();
						n.TypeNoeud="Fichier_SQL";
	    				n.MenuLibelle=ff.getName();
	    				n.MenuPath=ff.getFullPath().toString();
	    				n.CompteOracle=prefs.getString(PreferenceConstants.Oracle_Constants.ORA_USER);
	    				n.pathlog=pathlog;
		    			n.pathexportcsv=pathpref;
		    			n.lignedetexte=line.replace("'","@\"");
		    			vals.add(n);
					}
	    			}	    		
	    		}
	    	
		} catch (CoreException e) {
			e.printStackTrace();
		}
		return vals;
	}

	
	private static String bytestoTextfile(IFile fichier) {
		String lignes="";		
		try {		
			File textfile  = fichier.getRawLocation().makeAbsolute().toFile();
			FileInputStream ipssm;

			ipssm = new FileInputStream(textfile);

			InputStreamReader ipsrsm=new InputStreamReader(ipssm);
			BufferedReader brsm=new BufferedReader(ipsrsm);
			try {
				String ligne =brsm.readLine();
	
				while (ligne!=null){
					lignes+=ligne+System.getProperty("line.separator" );
					ligne =brsm.readLine();
				}
			} finally {
				brsm.close();
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return lignes;
	}
	private static Element bytestodocxml(IFile fichier) 
		   {
			   //System.out.println("Debut charge fichier xml");
			   Document doc=null;Element rac=null;
			try {
				
			     SAXBuilder sxb = new SAXBuilder();
			      File docxml  = fichier.getRawLocation().makeAbsolute().toFile();
			      doc = sxb.build(docxml);
			      rac=new  Element("base");
			      rac = doc.getRootElement();		
			} catch (Exception e) {
				e.printStackTrace();
			}
			return rac;
	}
	
	public static Vector<String> recursIressourceChild(String currentnoeud,IResource res,Vector<String> vals){
		try {
			String pathcomplet=currentnoeud+File.separator+res.getName();
	    	if (res.getType()==IResource.PROJECT){
	    		IResource[] resenf;
				resenf = ((IProject) res).members();
	        	for(IResource rr:resenf){
	        		recursIressourceChild(pathcomplet,rr,vals);
	        	}
	    	}
	    	if (res.getType()==IResource.FOLDER) {
	    		IResource[] resenf= ((IFolder) res).members();
	        	for(IResource rr:resenf){
	        		recursIressourceChild(pathcomplet,rr,vals);
	        	}
	    	}
	    	if (res.getType()==IResource.FILE){
	    		if (!pathcomplet.endsWith(".project") && !pathcomplet.endsWith(".run")) 
	    			vals.add(pathcomplet);	
	    		
	    	}
		} catch (CoreException e) {
			e.printStackTrace();
		}
		return vals;
	}
	
	static String escapeChar(String texte){

    	String tests = texte.replaceAll("-", "_");
    	tests=tests.replaceAll(Pattern.quote("/"), "_");
    	tests=tests.replaceAll(Pattern.quote("+"), "_");
    	tests=tests.replaceAll(Pattern.quote("."), "_");
    	tests=tests.replaceAll(Pattern.quote("\""), "_");
    	tests=tests.replaceAll(Pattern.quote("-"), "_");
    	
    	return tests;
		
	}
	public  IFile recursIressourceChildExec(String cible,String currentnoeud,IResource res,Vector<String> vals){
		try {
			IFile ff=null;
			String pathcomplet=currentnoeud+File.separator+res.getName();
	    	if (res.getType()==IResource.PROJECT){
	    		IResource[] resenf;
				resenf = ((IProject) res).members();
	        	for(IResource rr:resenf){
	        		ff=recursIressourceChildExec(cible,pathcomplet,rr,vals);
	        		if (ff!=null) return ff;
	        	}
	    	}
	    	if (res.getType()==IResource.FOLDER) {
	    		IResource[] resenf= ((IFolder) res).members();
	        	for(IResource rr:resenf){
	        		ff=recursIressourceChildExec(cible,pathcomplet,rr,vals);
	        		if (ff!=null) return ff;
	        	}
	    	}
	    	if (res.getType()==IResource.FILE){
	    		if (!pathcomplet.endsWith(".project")){
	    			vals.add(pathcomplet);	
	    			if (pathcomplet.equals(cible)){
	    				ff= (IFile) res;
	    				System.out.println(res.getFullPath());
	    				System.out.println(cible);
	    				return ff;
	    			}
	    		}
	    			
	    		
	    	}
		} catch (CoreException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	static Vector<String> listerRepertoire(File repertoire,String debut1,String debut2,String extention){ 

		 String [] listefichiers; 
		 Vector<String> listeext=new Vector<String>();
		 int i; 
		 listefichiers=repertoire.list(); 
		 for(i=0;i<listefichiers.length;i++){ 
			 if(listefichiers[i].endsWith(extention)==true && (listefichiers[i].startsWith(debut1) || listefichiers[i].startsWith(debut2))){ 
				 listeext.add(listefichiers[i]);
				 System.out.println(listefichiers[i]); 
			 } 
	     }
		 return listeext; 
	}
	
	public static MessageConsoleStream2out findOutConsole(String name){
		MessageConsole myConsole = Utils.findConsole(name);
		MessageConsoleStream2out out = new MessageConsoleStream2out(myConsole);
		   
		return out;
	}
	   
   private static MessageConsole findConsole(String name) {
	      ConsolePlugin plugin = ConsolePlugin.getDefault();
	      IConsoleManager conMan = plugin.getConsoleManager();
	      IConsole[] existing = conMan.getConsoles();
	      for (int i = 0; i < existing.length; i++) {
	         if (name.equals(existing[i].getName()))
	            return (MessageConsole) existing[i];
	      }
	      MessageConsole myConsole = new MessageConsole(name, null);
	      conMan.addConsoles(new IConsole[]{myConsole});
	      
	      return myConsole;
	}
   
// =============================================================================
// =============================================================================
   
	static void logInConsoleView(String message) {
		logInConsoleView(false, message, null);
	}
	
	static void logErrorInConsoleView(String message) { // NO_UCD (unused code)
		logInConsoleView(false, message, null);
	}
	
	static void logErrorInConsoleView(String message, Throwable t) {
		logInConsoleView(true, message, t);
	}

	static void logInBoxError(Exception ex, final String title, // NO_UCD (unused code)
									final String prefixMessage) {
		StringWriter writer = new StringWriter();
		ex.printStackTrace(new PrintWriter(writer));

		final String message = (prefixMessage == null ? "" : prefixMessage) 
									+ ex.getMessage(); 
		final Status status = new Status(IStatus.ERROR, Activator.PLUGIN_ID,
				message, new Throwable(writer.toString()));

		Activator.getDefault().getLog().log(status);
		Display.getDefault().asyncExec(new Runnable() {
			@Override
			public void run() {
				ErrorDialog.openError(Display.getDefault().getActiveShell(),
						title, message, status);
			}
		});
	}

	static void logInErrorLogView(String message, int severity) { // NO_UCD (unused code)
		Activator.getDefault().getLog()
				.log(new Status(severity, Activator.PLUGIN_ID, message));
		if (severity == IStatus.ERROR) {
			System.err.println(message);
		} else {
			System.out.println(message);
		}
	}

	static void logInErrorLogView(String message, Throwable e) { // NO_UCD (unused code)
		Activator.getDefault().getLog().log(new Status(IStatus.ERROR, 
										Activator.PLUGIN_ID, message, e));
		System.err.println(message);
	}

	private static void logInConsoleView(final boolean err, final String message, final Throwable e) {
		final MessageConsole myConsole = findConsole(DEFAULT_CONSOLE_NAME);
		
		if (err) {
			Display.getDefault().asyncExec(new Runnable() {
				public void run() {
					MessageConsoleStream stream = myConsole.newMessageStream();
					stream.setColor(COLOR_RED);
					if (message != null) {
						stream.println(message);
					}
					if (e != null) {
						e.printStackTrace(new PrintStream(stream));
					}
				}});
			toFrontConsole(DEFAULT_CONSOLE_NAME);
		} else {
			MessageConsoleStream stream = myConsole.newMessageStream();
			if (message != null) {
				stream.println(message);
			}
			if (e != null) {
				e.printStackTrace(new PrintStream(stream));
			}
		}		
	}

	private static void toFrontConsole(String consoleName) {
		try {
			IConsole myConsole = findConsole(consoleName);
			IWorkbenchWindow window = Activator.getDefault().getWorkbench().getActiveWorkbenchWindow();
			if (window != null) {
				IConsoleView view = (IConsoleView)window.getActivePage().showView(IConsoleConstants.ID_CONSOLE_VIEW);
				view.display(myConsole);
			}
		} catch (PartInitException e) {
			Activator
					.getDefault()
					.getLog()
					.log(new Status(IStatus.ERROR, Activator.PLUGIN_ID, null, e));
			e.printStackTrace();
		}
	}
	
	// TODO Remove unused code found by UCDetector
// 	public static Vector<String> recursIressourceChildHtml(String currentnoeud,IResource res,Vector<String> vals, run_editor thi, MessageConsoleStream out,String suffixe){
// 		try {
// 			String pathcomplet=currentnoeud+File.separator+res.getName();
// 			
// 			
// 	    	if (res.getType()==IResource.PROJECT){
// 	        	vals.add("<li><a href=\"#\"><b>"+res.getName()+"</b></a>");
// 	        	vals.add("<ul>");	    		
// 	        	IResource[] resenf;
// 				resenf = ((IProject) res).members();
// 				String suffi = res.getPersistentProperty(new QualifiedName("",SamplePropertyPage.UV_PROPERTY3));
// 	        	for(IResource rr:resenf){
// 	        		recursIressourceChildHtml(pathcomplet,rr,vals, thi, out,suffi);
// 	        	}
//         		vals.add("</ul>");
//         		vals.add("</li>");	        	
// 	    	}
// 	    	if (res.getType()==IResource.FOLDER) {
// 	        	vals.add("<li><a href=\"#\"><b>"+res.getName()+"</b></a>");
//         		vals.add("<ul>");
// 	    		IResource[] resenf= ((IFolder) res).members();
// 	        	for(IResource rr:resenf){
// 	        		recursIressourceChildHtml(pathcomplet,rr,vals, thi, out,suffixe);
// 	        	}
//         		vals.add("</ul>");
//         		vals.add("</li>");
// 	    	}
// 	    	if (res.getType()==IResource.FILE){
// 	    		if (pathcomplet.endsWith(".trf")) {
// 	    			Utils ut =new Utils();
// 	    			
// 	    			IFile ff=ut.recursIressourceChildExec(pathcomplet,currentnoeud,res,new Vector<String>());
// 	    			Element xmlfile=bytestodocxml(ff);
// 					if (xmlfile!=null && xmlfile.getName().equals("TRF_PARAM")){
// 						 String fichieruv=(xmlfile.getAttribute("FICHIERUV").getValue());
// 						 ObjetUniverse objUV =new ObjetUniverse(thi,out);
// 						 
// 						 objUV.setPathPHP(currentnoeud.replaceAll(Pattern.quote(File.separator), "_")+"_");
// 						 objUV.ChargementDesColonnes(xmlfile.getChild("Colonnes"), null,null);
// 						 objUV.DescSynchronisationUVOracle(fichieruv,suffixe);
// 						
// 					}
// 	    			String pathtrans=currentnoeud.replaceAll(Pattern.quote(File.separator), "_");
// 	    			pathtrans=Utils.escapeChar(pathtrans);
// 	    			if (xmlfile!=null) {
// 		    			pathtrans=pathtrans.replaceAll(" ", "_") + "_"+Utils.escapeChar(xmlfile.getAttribute("FICHIERUV").getValue());
// 		    			vals.add("<li><a href=\"?path="+pathtrans+"\"><u>"+xmlfile.getAttribute("FICHIERUV").getValue()+"</u></a>");
// 		    		    vals.add("</li>");
// 	    			}
// 	    		}
// 	    		
// 	    		if (pathcomplet.endsWith(".sql")) {		
// 	    			Utils ut =new Utils();
// 	    			IFile ff=ut.recursIressourceChildExec(pathcomplet,currentnoeud,res,new Vector<String>());
// 	    			String textfile=bytestoTextfile(ff);
// 	    			if (textfile.contains("POUR CONTROLE")) {
// 		    			ObjetOracle objOra = new ObjetOracle(null);
// 		    			
// 		    			objOra.DescSynchronisationUVOracle(ff.getName(),ff.getFullPath().toString(), textfile);
// 		    			String pathtrans=currentnoeud.replaceAll(Pattern.quote(File.separator), "_");
// 		    			pathtrans=Utils.escapeChar(pathtrans);
// 		    			pathtrans=pathtrans.replaceAll(" ", "_") + "_"+Utils.escapeChar(ff.getName());
// 			    		vals.add("<li><a href=\"?path="+pathtrans+"\"><u>"+ff.getName()+"</u></a>");
// 			    		vals.add("</li>");	    				
// 	    			}
// 
// 	    			}	    		
// 	    		}
// 	    	
// 		} catch (CoreException e) {
// 			e.printStackTrace();
// 		}
// 		return vals;
// 	}
}
